import BaseCommand from "@/core/Frame/BaseClass/BaseCommand";
import * as turf from "@turf/turf";
import store from "@/store";
const PIE = window.PIE;
const EarthDraw = window.EarthDraw;
const iconID = 1;

// 新建点线面
class DrawAddCommand extends BaseCommand {
  viewer: any;
  eventsManager: any;
  widgetsManager: any;
  globeControl: any;
  globe: any;
  globeEditor: any;
  workspace: any;
  renderableLayer: any;
  earthDraw: any;
  option: any;
  optionGroup: any;
  lastCheckedOption: any;
  needCheckedList: any;
  inputEl:any;
  hasAdd:any;
  constructor(params: any) {
    super();
    this.viewer = params.viewer; // 地球对象
    this.eventsManager = params.eventsManager; // 发布订阅对象
    this.widgetsManager = params.widgetsManager; // 组件管理对象
    this.globeControl = this.viewer.getGlobeControl();
    this.globe = this.globeControl.getGlobe();
    this.globeEditor = this.globeControl.getGlobeEditor(); //获取场景编辑器
    this.workspace = this.globe.getDocument(); // 获取工作空间
    this.renderableLayer = null; // 创建绘制对象图层，添加在场景中
    this.earthDraw = new EarthDraw.setup(this.viewer, {});
    // this.earthDraw = new window.EarthDraw(this.viewer, {});
    // window.earthDraw = this.earthDraw;
    // window.globe = this.globe;
    // window.globeControl = this.globeControl;
    //设置锚点大小
    this.earthDraw.ctx.vertexsControl.setDefaultSize(10);
    this.earthDraw.ctx.vertexsControl.setActiveSize(15);
    this.lastCheckedOption = null; //记录上次选中option（添加、移除状态),用于还原按钮选中
    this.needCheckedList = [
      "edit_addPoint",
      "edit_addLine",
      "edit_addPlolygon",
      "edit_addNode",
      "edit_removeNode",
      "edit_addText",
    ]; //需要还原的按钮'多边形','矩形','圆',
    this.optionGroup = {}; //按钮状态列表
    //监听图层变化,设置编辑图层
    this.eventsManager.on("EditLayerChangedEvent", (layer: any) => {
      console.log("编辑图层变化");
      this.earthDraw.setEditedLayer(layer.layer);
    });

    this.earthDraw.ctx.listener.on("selectFeature", (feature: any) => {
      console.log(feature);
      let featureType = feature.feature.type;
      if (
        featureType == "text" ||
        featureType == "point" ||
        featureType == "circle" ||
        featureType == "rect" ||
        featureType == "bezier"
      ) {
        //点、圆、矩形、贝塞尔曲线 无法添加或者删除节点
        this.optionGroup["edit_addNode"].enable = false;
        this.optionGroup["edit_removeNode"].enable = false;
        // option.enable = false;
        if (featureType == "text") {
          feature.feature.vertexs
          let mousePosition = this.globe.mapToDevice(feature.feature.vertexs[0])
          setTimeout(() => {
            this.showInputEl(feature, [mousePosition.x, mousePosition.y], true);
          this.hasAdd = true
          }, 0);
          
        }
      } else {
        //线  面  可以操作节点
        this.optionGroup["edit_addNode"].enable = true;
        this.optionGroup["edit_removeNode"].enable = true;
      }
      this.optionGroup["edit_delete"].enable = true;
      this.optionGroup["edit_copy"].enable = true;
      // this.optionGroup['edit_paste'].enable = this.earthDraw.ctx.store._copyFeatures.length>0;;
    });

    this.earthDraw.ctx.listener.on("clearSelect", () => {
      // console.log("没有选中");
      this.optionGroup["edit_addNode"].enable = false;
      this.optionGroup["edit_removeNode"].enable = false;
      this.optionGroup["edit_delete"].enable = false;
      this.optionGroup["edit_copy"].enable = false;
      // this.optionGroup['edit_paste'].enable = false;
    });

    this.earthDraw.ctx.listener.on('draw.commit', (feature: any) => {
      console.log('draw.commit');
    });
    this.earthDraw.ctx.listener.on('draw.update', (feature: any) => {
      console.log('draw.update');
      let parent = feature.feature._ctx.container.parentElement;
      if(this.inputEl && this.hasAdd  && parent.contains(this.inputEl)){
        parent.removeChild(this.inputEl);
        this.inputEl=null;
        this.hasAdd=false;
      }
    });
    this.earthDraw.ctx.listener.on("draw.create", (feature: any) => {
      console.log("draw.create");
      //判断文本
      if (feature.feature.type != "text") return;
      //等刷新坐标之后再获取坐标
      let mousePosition = feature.feature._ctx.events.currentMode.mouseDownPosition;
      let vec2 = this.globe.deviceToMap(mousePosition)
      if (vec2.x == 0 && vec2.y == 0) {
        //点在球外面
        return;
      }
      //默认文本先置空
      feature.feature.style.text = "";
      this.earthDraw.ctx.store.commitFeature(feature.feature, false, false);

      this.showInputEl(feature, mousePosition, false);
      setTimeout(() => {
        this.hasAdd = true;
      }, 0);
    });
    let drawOverFn = () => {
      //第一次绘制完成赋值撤销按钮可用
      this.optionGroup["edit_undo"].enable = true; //this.earthDraw.ctx.operationList.canUndo()
      this.earthDraw.ctx.listener.un("draw.commit", drawOverFn);
    };
    this.earthDraw.ctx.listener.on("draw.commit", drawOverFn);
  }
  showInputEl(feature: any, mousePosition: any, isEdit: any): void {
    //创建输入框
    let inputEl = document.createElement("input");
    inputEl.type = "textarea";
    //判断边界,input宽高为200px,36px
    let css_left = mousePosition[0],
      css_top = mousePosition[1];
    if (css_left + 200 > feature.feature._ctx.container.width) {
      css_left = feature.feature._ctx.container.width - 200;
    } else {
      // 左对齐

      // 居中对齐
      css_left -= 100

    }
    if (css_top + 36 > feature.feature._ctx.container.height) {
      css_top = feature.feature._ctx.container.height - 36;
    }
    inputEl.style.cssText = `position:absolute;left:${css_left}px;top:${css_top - 36 - 5}px`;
    // inputEl.autofocus = true;
    inputEl.placeholder = "文字输入";
    isEdit && (inputEl.value = feature.feature.style.text);
    inputEl.classList.add("el-input__inner", "textInput");
    inputEl.onblur = (e: any) => {
      console.log(111);
      let text = e.target.value.trim();
      if (text == "") {
        //删除空文本
        if (isEdit) {
          this.earthDraw.ctx.store.deleteFeature(feature.feature);
        } else {
          this.earthDraw.ctx.store.deleteFeature(feature.feature);
        }
      } else {
        if (feature.feature.style.text == text) {

        } else {
          feature.feature.style.text = text;
          this.earthDraw.ctx.store.commitFeature(
            feature.feature,
            !isEdit,
            true
          );
        }
      }
      // feature.feature._ctx.container.parentElement.removeChild(e.target);
      setTimeout(() => {
        let parent =  feature.feature._ctx.container.parentElement;
        if(parent.contains(e.target)){
          parent.removeChild(e.target);
        };
      }, 0);
      this.inputEl=null;
      this.hasAdd = false;
    };
    feature.feature._ctx.container.parentElement.appendChild(inputEl);
    inputEl.focus();
    this.inputEl=inputEl;
  }
  execute(option: any): void {
    this.option = option;
    console.log(option);
    // console.log("execute");
    this.menuChange(option.paramter.methods);
    setTimeout(() => {
      let needRefreshLast = true;
      if (
        this.lastCheckedOption &&
        this.needCheckedList.indexOf(this.lastCheckedOption.id) > -1
      ) {
        //需要保持上次选中状态
        if (this.needCheckedList.indexOf(this.option.id) > -1) {
        } else if (option.id == "edit_select") {
          this.earthDraw.changeMode("simple_select");
        } else {
          let name = option.name;
          if (
            name == "多边形" ||
            name == "圆" ||
            name == "矩形" ||
            name == "折线" ||
            name == "贝塞尔曲线"
          ) {
            //手动取消选中
            this.optionGroup["edit_addPoint"].checked = false;
            this.optionGroup["edit_addText"].checked = false;
          } else {
            //还原上次选中按钮
            this.optionGroup[this.lastCheckedOption.id].checked = true;
            needRefreshLast = false;
          }
        }
      }
      needRefreshLast &&
        (this.lastCheckedOption = JSON.parse(JSON.stringify(option)));
      //判断是否有选中的符号，选中的类型点、圆、矩形、贝塞尔曲线、文本无法操作节点，其余的可以操作节点。
      let features = this.earthDraw.getSelectedFeatures();
      let canOperateNode = true;
      if (features.length > 0) {
        for (let i = 0; i < features.length; i++) {
          let type = features[i].type;
          switch (type) {
            case "point":
            case "circle":
            case "rect":
            case "bezier":
            case "text":
              {
                canOperateNode = false;
              }
              break;
          }
          if (!canOperateNode) break;
        }
      } else {
        canOperateNode = false;
        this.optionGroup["edit_delete"].enable = false;
        this.optionGroup["edit_copy"].enable = false;
      }
      if (!canOperateNode) {
        this.optionGroup["edit_addNode"].enable = false;
        this.optionGroup["edit_removeNode"].enable = false;
      }

      //模型编辑判断,操作模型时关闭其他按钮
      let id = this.option.id;
      let modeIdList = [
        "edit_translate",
        "edit_height_adjustment",
        "edit_rotate",
        "edit_zoom",
      ];
      if (modeIdList.indexOf(id) > -1) {
        // this.earthDraw.destroy();
        for (const key in this.optionGroup) {
          if (modeIdList.indexOf(key) < 0) {
            this.optionGroup[key].enable = false;
          }
        }
      }
    }, 0);
  }
  menuChange(menuName: string) {
    if (this.option.paramter.mode == "changeMode") {
      // 绘制、编辑、节点
      if (menuName == "draw_text") {
        const textColor = PIE.Color.fromCssColorString("#ffffff");
        const textStyle = new PIE.TextStyle();
        textStyle.setForeColor(textColor);
        // textStyle.setBackColor(textColor);
        textStyle.setWidth(20);
        textStyle.setHeight(20);
        textStyle.setFaceName("16px Helvetica");
        // textStyle.setAlign(PIE.TextAlignType.LeftCenter);
        textStyle.setAlign(PIE.TextAlignType.Center);
        this.earthDraw.changeMode(menuName, {
          pieStyle: textStyle,
          saveOperation: false,//画文本不存储初始步骤
        });
      } else {
        this.earthDraw.changeMode(menuName);
      }
    } else {
      let method = this.option.paramter.methods;
      switch (method) {
        case "undo": // 撤销
        case "redo":
          // 重做
          this.earthDraw.ctx.operationList[method]();
          break;
        case "delete":
          // 删除
          this.earthDraw.removeSelectedFeatures();
          //点击删除之后删除按钮置灰
          this.optionGroup["edit_delete"].enable = false;
          break;
        case "closeDraw":
          //结束绘制
          this.earthDraw.destroy();
          //设置编辑图层为null，刷新按钮状态
          store.commit("changLayer", null);
          break;
        case "openDraw":
          // 开始绘制
          this.earthDraw.connect();
          break;
        case "catchPoint": //节点捕捉
        case "catchLine":
        case "catchKneePoint":
          this.earthDraw.ctx[method] = true;
          break;
        case "copy":
          this.earthDraw.ctx.store.copyFeatures();
          break;
        case "paste":
          this.earthDraw.ctx.store.pasteFeatures();
          break;
        case "editTranslate": //模型编辑
        case "editHeightAdjustment":
        case "editRotate":
        case "editZoom":
          //earthDraw切换为默认状态,不用销毁
          this.earthDraw.changeMode(null);
          this.earthDraw.ctx.store.clearSelectedFeatures();
          this.earthDraw.ctx.vertexsControl.destroy();

          let toolType = this.option.paramter.toolType;
          let currlayer = store.state.menu.selectLayer.layer;
          var globeEditor = this.globeControl.getGlobeEditor();
          globeEditor.setEditLayer(currlayer);
          globeEditor.setEditMode(PIE.EditMode.Geometry3D);
          // console.log("currlayer", currlayer);
          currlayer.setSelectable(true);
          this.globeControl.setGlobeTool(PIE.GlobeToolType[toolType]);

          break;
        default:
          break;
      }
    }
  }
  // true代表功能可用，如果是false代表功能不可用
  isEnable(option: any): boolean {
    // console.log(option)
    if (!this.optionGroup.hasOwnProperty(option.id)) {
      this.optionGroup[option.id] = option;
    }

    let currlayer = store.state.menu.selectLayer;

    if (!currlayer || !currlayer.hasOwnProperty("id")) {
      //没有选择的图层，禁止相关操作
      return false;
    }
    switch (option.id) {
      // case 'edit_addPoint':
      // case 'edit_addLine':
      // case 'edit_addPlolygon': {
      //   return true;
      // } break;
      // case 'edit_copy':{
      //   return this.earthDraw.getSelectedFeatures().length > 0
      // }break;
      case "edit_paste":
        return this.earthDraw.ctx.store._copyFeatures.length > 0;
        break;
      case "edit_copy":
      case "edit_addNode":
      case "edit_removeNode":
      case "edit_delete":
        return this.optionGroup[option.id].enable;
        break;
      case "edit_undo":
        //撤销
        return this.earthDraw.ctx.operationList.canUndo();
        break;
      case "edit_redo":
        //重做
        return this.earthDraw.ctx.operationList.canRedo();
        break;
      //暂未开放
      case "edit_cut": //裁剪
      case "edit_combine": //合并
      case "edit_split": //拆分
      case "edit_intersect": //求交
        return false;
        break;
      case "edit_translate": //模型编辑
      case "edit_height_adjustment":
      case "edit_zoom":
      case "edit_rotate":
        return currlayer.layer.getType() == PIE.GlobeLayerType.Renderable;
        break;
      default:
        return true;
        break;
    }
  }
  release(option: any): void {
    // console.log(option, 1111111111);
    switch (option.id) {
      case "edit_addPoint":
      case "edit_addLine":
      case "edit_addPlolygon":
      case "edit_addNode":
      case "edit_addText":
      case "edit_removeNode":
        if (!option.checked) {
          this.earthDraw.changeMode("simple_select");
          //取消选中本身时清空上次选中
          this.lastCheckedOption = null;
        }
        break;
      case "edit_catchPoint":
      case "edit_catchLine":
      case "edit_catchKneePoint":
        let setCatchProperty = option.id.slice(5);
        this.earthDraw.ctx[setCatchProperty] = false;
        break;
      case "edit_translate":
      case "edit_height_adjustment":
      case "edit_zoom":
      case "edit_rotate":
        if (option.checked) {
          //切换
        } else {
          //释放本身
          let globeEditor = this.globeControl.getGlobeEditor();
          globeEditor.setEditMode(PIE.EditMode.Default);
          this.globeControl.setGlobeTool(PIE.GlobeToolType.Pan);
          console.log("release");
          // this.earthDraw.connect();
          // this.earthDraw.setEditedLayer(store.state.menu.selectLayer.layer);
        }
        break;
      default:
        break;
    }
  }
}

export default DrawAddCommand;
